<template>
  <div class="c-f" style="max-width:750px;width:80%;" >
    <div>
       <!--头部-->
      <div id="navbar" class="p-15 boot-bg">
        <div >
          <div v-if="this.$store.state.currentToId">
            {{this.$store.state.currentToId.nickName}}
          </div>
          <div v-else>正在连接...</div>
        </div>
      </div>
      <!-- 中间聊天内容区域 -->
      <div id="main"  ref="ctx" class="c-f chat_bg_panel" :style="{'max-height':slide_h,'height':slide_h}" style="overflow-y: auto">
        <div v-for="(x,index) in $store.getters.getValForKey('channels')" :key="index" >
          <div v-if="x.sid===$store.getters.getValForKey('currentToId').sid">
            <div  v-for="(y,key) in x.logs"  :key="key">
              <div  class="p-10">
                <div class="text-center p-tb5" v-if="key==0||(key>1&&((y.sendTime-x.logs[key-1].sendTime)>$store.state.HEARTBEAT_TIME))" style="right:10px"><span class="chat_bg_time title12">{{proUtil.formatDate(proUtil.getTimeByTimeZone(8,(y.sendTime/1000*1000)),"hh:mm")}}</span></div>
                <div class="p-relative">
                  <div class="pull-left w-50 text-right" :class="{'pull-right text-left':y.sid===cid}">
                    <div class="c-9 lue title12 breakAll">{{y.sid===cid?y.sname:$store.state.currentToId.sname}}</div>
                  </div>
                  <div class="overflow   p-lr10" :class="{'text-right':y.sid===cid}">
                    <div class="text-left chat_bg  breakAll chat_txt"  :style="{'max-width':chat_w}" :class="{'chat_bg_my':y.sid===cid}"v-text="y.ctx"></div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- 底部输入框 -->
      <div>
        <div id="iminput">
          <el-input  placeholder="请输入信息" v-model="msg">
            <template slot="append"><div @click="tosend()" class="cursor" >发 送</div></template>
          </el-input>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
  import IMMessage from '@/utils/im/IMMessage';
  export default {
    name: "imService",
    data() {
      return {
        visible: false,
        navinfo: {
          title: this.$store.state.currentToId==""?'在线客服...':this.$store.state.currentToId.nickName,
          leftText: '返回',
          leftIcon: '',
          leftLink: '',
          rightText: '',
          rightIcon: '',
          rightLink: 'showpop'
        },
        screenH:window.document.body.offsetHeight+'px',
        slide_h: (window.document.body.offsetHeight - 216) + "px",
        chat_w: (window.document.body.offsetWidth*0.5) + "px",
        cmdLen:this.$store.getters.getValForKey("cmdLen"),
        CMD:this.$store.getters.getValForKey("CMD"),
        CMDHander:this.$store.getters.getValForKey("CMDHander"),
        CMDReverse:{},
        msg: "",
        cid:'c'+this.$store.getters.getUserInfo.id,
      }
    },
    methods: {
      init(){
        if(this.$store.state.ws==null){
          this.$router.go(-1);
          // this.proUtil.msgInfo("初始化异常",1);
          return;
        }
        this.initCMDReverse();
        this.$store.state.ws.onmessage = (event, ws) => {
          var arrayBuffer = event.data;
          // console.log('receive data: ', arrayBuffer, ws)
          var uint8array = null;
          var firstbyte = new Uint8Array(arrayBuffer, 0, 2);
          var firstchar = new TextDecoder('utf-8').decode(firstbyte);
          var isZipped = false;
          var isZippedStr = '';
          if (firstchar.indexOf('x') != -1) {
            // 压缩过的
            isZipped = true;
            isZippedStr = '(zipped)';
            var zipedUint8array = new Uint8Array(arrayBuffer, 2);
            uint8array = pako.ungzip(zipedUint8array);
          } else {
            uint8array = new Uint8Array(arrayBuffer);
          }
          var data = new TextDecoder('utf-8').decode(uint8array);
          console.log('receive data' + isZippedStr + ': ' + data)
          if (!data || data.length < this.cmdLen) {
            console.error('data wrong' + isZippedStr + ', the data length must be >= ' + this.cmdLen, data);
            return;
          }
          var commandstr = data.substr(0, this.cmdLen);
          console.log(commandstr);
          var commandName = this.CMDReverse[commandstr];
          if (!commandName) {
            console.error('commandstr is ' + commandstr + isZippedStr + ', but con not find commandName');
            return;
          }
          if (!this.CMDHander[commandName]) {
            console.error('can not found siteImBsHandler, commandName is ' + commandName + isZippedStr);
            return;
          }
          if (data.length > this.cmdLen) {
            var bodyStr = data.substr(this.cmdLen);

            console.log('received:' + commandName + isZippedStr + '\r\n, body string is :' + bodyStr);
            var bodyObj = null;
            try {
              bodyObj = JSON.parse(bodyStr);
              console.log(bodyObj);
            } catch (error) {
              console.error(
                'can not parse to object, commandName is ' +
                commandName +
                isZippedStr +
                ', body string is ' +
                bodyStr
              );
              return;
            }
            // console.log("received " + commandName + ", body string is :" + bodyStr);
            this.CMDHander[commandName](this.$store.state.ws, event, commandName, bodyStr, bodyObj,this.$store);
          } else {
            console.log('received:' + commandName + isZippedStr + ', body string is null');
            this.CMDHander[commandName](this.$store.state.ws, event, commandName, null, null,this.$store);
          }
        };
        // this.joingroup();

        this.getCustomList();
      },
      initCMDReverse(){
        for (var cmdName in this.CMD) {
          var commandValue = this.CMD[cmdName];
          this.CMDReverse[this.formatCommand(commandValue)] = cmdName;
        }
        console.log(this.CMDReverse);
      },
      tosend(){
        if(this.$store.getters.getValForKey("currentToId")==""){
          return;
        }
        if(this.msg.trim()==""){
          return;
        }
        this.sendInfo(
          this.CMD.P2P_CHAT_REQ,
          new IMMessage(
            this.$store.getters.getValForKey("currentToId").sid,
            this.$store.getters.getUserInfo.id,
            this.msg,
            this.$store.getters.getValForKey("currentToId").sname,
            this.$store.getters.getUserInfo.userName
          )
        );
      },
      // joingroup(groupId){
      //   this.$toast.loading({
      //     mask: true,
      //     duration:300,
      //     message: '连接客服...'
      //   });
      //   this.sendInfo(this.CMD.JOIN_GROUP_REQ,new IMMessage(groupId==null?"":groupId,this.$store.getters.getUserInfo.id,""));
      // },
      getCustomList(){
        //获取客服列表
        const maskloding = this.$loading({
          target:"app",
          body:false,
          fullscreen:true,
          lock:true,
          text:"连接客服...",
          background:"rgba(0,0,0,0.5)"
        });
        this.sendInfo(this.CMD.ALL_CHAT_ROMM_REQ,new IMMessage("",this.$store.getters.getUserInfo.userName,"","",""));
        setTimeout(()=>{
          maskloding.close();
        },800)
      },
      sendInfo(command, bodyObj) {
        if(!this.$store.state.ws||this.$store.state.ws.readyState!=1){
          console.error("ws状态不正确");
          clearTimeout(this.clock);
          return;
        }
        console.log(this.CMDReverse);
        var commandname = this.CMDReverse[command];
        var str = command;
        if (bodyObj) {
          str = command + JSON.stringify(bodyObj);
        }
        console.log('准备发送 ' + commandname + ":'" + str + "'");
        var uint8array = new TextEncoder().encode(str);
        this.$store.state.ws.send(uint8array.buffer);
        this.msg="";
      },
      formatCommand(command){
        var commandstr = command + "";
        if (commandstr.length < this.cmdLen) {
          var gap = this.cmdLen - commandstr.length;
          var supplystr = "";
          for (var index = 0; index < gap; index++) {
            supplystr += "0";
          }
          if (command < 0) {
            commandstr = "-" + supplystr + commandstr.substring(1);
          } else {
            commandstr = supplystr + commandstr;
          }
        }
        return commandstr;
      }
    },
    beforeCreate: function () {
    },
    created: function () {
    },
    beforeMount: function () {
    },
    mounted: function () {

    },
    updated: function () {
      this.$nextTick(function(){
        // var div = document.getElementById('main');
        // div.scrollTop = div.scrollHeight;
        this.$refs.ctx.scrollTop = this.$refs.ctx.scrollHeight;
      })
    },
    activated: function () {
    },
    deactivated: function () {
    },
    beforeDestroy: function () {
    },
    destroyed: function () {
    },
    errorCaptured: function (err, vm, info) {
    },
    beforeRouteEnter(to,from,next){
      console.log("22");
      if(to.query.ws!=null&&to.query.ws.readyState==1){
        next(vm =>vm.init());
      }else{
        next("/home")
      }
    },
    beforeRouteLeave(to,from,next){
      console.log("123");
      if(this.$store.getters.getUserInfo!=null){
        // this.sendInfo(this.CMD.LEAVE_GROUP_REQ,new IMMessage("",this.$store.getters.getUserInfo.id,""));
        if(this.$store.state.ws){
          this.$store.state.ws.removeEventListener('message', function (event) {
            console.log('Message from server ', event.data);
          });
        }
      }
      next();
    }
  }
</script>
<style scoped>
  .circle {
    margin: 0 auto;
    width: 30px;
    height: 30px;
    line-height: 30px;
    border-radius: 15px;
    font-size: 16px
  }

  .active {
    background-color: #ef0000;
    color: #fff;
  }

  .numpanel {
    width: 40;
    height: 40px;
    margin-right: 5px;
  }
  .van-nav-bar__title,.van-nav-bar__text,.van-icon {
    color:#ffffff;
  }
  #navbarMain>>>.van-nav-bar__text:active{
    background-color: transparent;
    color:#00aeef;
  }
  #navbarMain>>>.van-nav-bar__text{
    background-color: transparent;
    color:#ffffff;
  }
  #navbarMain>>>.van-icon{
    color:#ffffff;
  }
  #iminput>>>.el-input__inner{
    border-radius:0
  }
  #iminput>>>.el-input-group__append, .el-input-group__prepend{
    border-radius: 0;
    background-color: #00aeef!important;
    color:#ffffff;
    border: #00aeef;
  }
</style>
